package com.ikun.admin.modules.auth.filter;

import com.alibaba.fastjson.JSON;
import com.ikun.common.constant.RedisConstant;
import com.ikun.common.exception.MyException;
import com.ikun.common.manager.RedisManager;
import com.ikun.starters.jwt.IJwtMemberDataService;
import com.ikun.starters.jwt.ITokenService;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author ximeng
 * @title: AuthFilter 认证拦截器
 */

public class AuthFilter extends BasicAuthenticationFilter {


    private ITokenService tokenService;

    private IJwtMemberDataService jwtMemberDataService;

    private RedisManager redisManager;


    private String tokenKey;

    public AuthFilter(AuthenticationManager authenticationManager, ITokenService tokenService, IJwtMemberDataService jwtMemberDataService, RedisManager redisManager, String tokenKey) {
        super(authenticationManager);
        this.tokenService = tokenService;
        this.jwtMemberDataService = jwtMemberDataService;
        this.redisManager = redisManager;
        this.tokenKey = tokenKey;
    }

    /**
     * 认证
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {


        String token = request.getHeader(this.tokenKey);
        if (token == null) {
            token = request.getParameter(this.tokenKey);
        }

        boolean tag = verify(token);
        if (tag) {
            String roleAndPermString = redisManager.getString(RedisConstant.USER_PERM_PREFIX+token);
            //将这个信息弄成List集合
            List<String> stringList = JSON.parseArray(roleAndPermString, String.class);
            Authentication authentication = getAuthtication(stringList, token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        chain.doFilter(request, response);
    }

    /**
     * 将权限角色信息封装成Authentication对象返回
     *
     * @param stringList
     * @param token
     * @return
     */
    private Authentication getAuthtication(List<String> stringList, String token) {
        String userId = jwtMemberDataService.getUserId(token);
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        if (Objects.isNull(stringList) || stringList.size() == 0) {
            throw new MyException("权限过期");
        }
        for (int i = 0; i < stringList.size(); i++) {
            //权限或者角色
            String permAndRole = stringList.get(i);

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permAndRole);
            grantedAuthorityList.add(simpleGrantedAuthority);
        }
        return new UsernamePasswordAuthenticationToken(userId, token, grantedAuthorityList);
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    private boolean verify(String token) {
        return tokenService.verifyToken(token);
    }
}
